<?php if(!defined('DB_NAME')) die();

// 主题设置相关
if( get('ini_fancybox') ) add_filter('the_content','ini_fancybox');   # Fancybox幻灯片
if( get('ini_index')=="显示" && function_exists('themedie') && !ismobile() ) add_filter( "the_content", "ini_index" );  # 文章索引

// 分页
function pagination( $query_string, $posts_per_page, $adjust=0 ){
	global $paged;
	$my_query = new WP_Query($query_string ."&posts_per_page=-1");
	$total_posts = $my_query->post_count;
	if( empty($paged) )$paged = 1;
		$prev = $paged - 1;
		$next = $paged + 1;
		$range = 3;   #分页数目
		$showitems = ($range * 2)+1;
		$pages = ceil($total_posts/$posts_per_page);
	if(0 != $pages){
		echo "<div class='pagination'";
		if( $adjust==1 ) echo " style=margin-top:0";
		echo ">";
		echo ( $paged > 2 && $paged+$range+1 > $pages && $showitems < $pages )? "<a href='".get_pagenum_link(1)."' class='fir_las'>&lt;&lt;</a>":"";
		echo ( $paged > 1 && $showitems < $pages )? "<a href='".get_pagenum_link($prev)."' class='page_prev'>&lt;</a>":"";
		for ($i=1; $i <= $pages; $i++){
			if( 0 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ) ){
				echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."'>".$i."</a>"; 
			}
		}
		echo ($paged < $pages && $showitems < $pages) ? "<a href='".get_pagenum_link($next)."' class='page_next'>&gt;</a>" :"";
		echo ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) ? "<a href='".get_pagenum_link($pages)."' class='fir_las'>&gt;&gt;</a>":"";
		echo "</div>";
	}
}

//标签配色
function ini_color(){
	$color1 = get('ini_color1')? get('ini_color1'): '#F88';
	$color2 = get('ini_color2')? get('ini_color2'): '#8D5';
	$color3 = get('ini_color3')? get('ini_color3'): '#D6D';
	$color4 = get('ini_color4')? get('ini_color4'): '#F96';
	$color5 = get('ini_color5')? get('ini_color5'): '#4BD';
	$color6 = get('ini_color6')? get('ini_color6'): '#F8A048';
	$color7 = get('ini_color7')? get('ini_color7'): '#3B9';
	$color8 = get('ini_color8')? get('ini_color8'): '#68F';
	$color9 = get('ini_color9')? get('ini_color9'): '#FD5';
	return array( $color1, $color2, $color3, $color4, $color5, $color6, $color7, $color8, $color9 );
}

// 文章摘要
function ini_excerpt( $count = 160 ){
	global $post;
	if ( has_excerpt() ){
		$content = get_the_excerpt();   #首选摘要
	}
	elseif ( get_post_meta($post->ID,'description',true) ){
		$description = trim( get_post_meta($post->ID, 'description', true) );   #无摘要则使用描述
		$content = mb_strimwidth( $description, 0, $count, "...");
	} else {
		$str = mb_strimwidth( strip_tags( apply_filters('the_content', $post->post_content) ), 0, $count, "...");
		$str = mb_ereg_replace('^(　| )+', '', $str);
		$str = mb_ereg_replace('(　| )+$', '', $str);
		$content = mb_ereg_replace( "\n", "", $str);
	}
	echo $content;
}

// 判断是否媒体文章
function ismedia(){
	if( is_single() ){
		$custom_fields = get_post_custom_keys($post_id);
		if( in_array('music', $custom_fields ) || in_array( 'video', $custom_fields) ){
			return true;
		}
	}
	return false;
}

// 截取文字
if( !function_exists('utf8_str') ){
	function utf8_str($str, $from, $len){
		return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
		'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
		'$1',$str);
	}
}

// 字数统计
function ini_count($text){
	global $post;
	if( '' == $text ){
		$text = $post->post_content;
		if( mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8') ) $output .= mb_strlen(preg_replace( '/\s/','',html_entity_decode( strip_tags( $post->post_content) ) ),'UTF-8');
		return $output;
	}
}

// 判断存在于子分类中
function in_des_cat( $cats, $_post = null ){
	foreach ( $cats as $cat ){
		$descendants = get_term_children( $cat,'category');
		if( $descendants && in_category( $descendants, $_post) )
		return true;
	}
	return false;
}

// 图片添加alt属性
function ini_alt( $imgalt ){
	global $post;
	$title = $post->post_title;
	$imgUrl = "/<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>/siU";
	if( preg_match_all("$imgUrl",$imgalt,$matches,PREG_SET_ORDER) ){
		if( !empty($matches) ){
			for ($i=0; $i < count($matches); $i++){
				$tag = $url = $matches[$i][0];
				$judge = '/alt=/';
				preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
				if( count($match) < 1 )
				$altURL = ' alt="'.$title.'"';
				$url = rtrim($url,'/>');
				$url .= $altURL.'/>';
				$imgalt = str_replace($tag,$url,$imgalt);
			}
		}
	}
	return $imgalt;
}
add_filter( 'the_content','ini_alt');
add_filter( 'comment_text','ini_alt');

// 禁用自带转义
remove_filter('the_content', 'wptexturize');

// code标签转义HTML实体
function escapeCE($arr){
	if(version_compare(PHP_VERSION, '5.2.3') >= 0){ // 所需PHP版本
		$output = htmlspecialchars($arr[2], ENT_NOQUOTES, get_bloginfo('charset'), false);
	} else {
		$needTo = array( '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' );
		$data = htmlspecialchars_decode($arr[2]);
		$output = strtr($data, $needTo);
	}
	if( !empty($output) ){
		return  $arr[1].$output.$arr[3];
	}
	else {
		return  $arr[1].$arr[2].$arr[3];
	}
}
function replaceCE($data){
	$replaceTag = preg_replace_callback('@(<code.*>)(.*)(</code>)@isU', 'escapeCE', $data);
	return $replaceTag;
}
add_filter( 'the_content', 'replaceCE');
add_filter( 'comment_text','replaceCE');

//文字标签
function i_tags(){
	$posttags = get_the_tags();
	if($posttags){
		foreach($posttags as $tag){
			$tag_link = get_tag_link($tag->term_id);
			$output.= '<a href="'.$tag_link.'" rel="tag">'.$tag->name.'</a>、';
		}
		$output = substr($output,0,strlen($output)-3);
		return $output;
	}
}

//彩色标签
function ini_tags(){
	$colors = ini_color();
	$posttags = get_the_tags();
	if($posttags){
		$output = "";
		foreach($posttags as $tag){
			$tag_link = get_tag_link($tag->term_id);
			$color = $colors[ rand(0,8) ]; #0到8共九种颜色
			$output.= "<a style='background:$color' href='$tag_link' rel='tag'>{$tag->name}</a>  ";
		}
		$output = substr($output,0,strlen($output)-2);
		echo "<div class='tags'>$output</div>";
	}
}

// 站外链接添加nofollow和新窗口打开
function ini_nofollow( $content ){
	$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
	if( preg_match_all("/$regexp/siU",$content,$matches,PREG_SET_ORDER) ){
		if( !empty($matches) ){
			$srcUrl = get('siteurl');
			for ($i=0; $i < count($matches); $i++)
			{
				$tag = $matches[$i][0];
				$tag2 = $matches[$i][0];
				$url = $matches[$i][0];
				$noFollow = '';
				$pattern1 = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
				$pattern2 = '/#title-/';
				preg_match($pattern1,$url,$match1,PREG_OFFSET_CAPTURE);
				preg_match($pattern2,$url,$match2,PREG_OFFSET_CAPTURE);
				if( count($match1) < 1 && count($match2) < 1 )
					$noFollow .= ' rel="external nofollow" ';
				$pos = stripos($url,$srcUrl);
				if($pos === false){
					$tag = rtrim ($tag,'>');
					$tag .= $noFollow.'>';
					$content = str_replace($tag2,$tag,$content);
				}
			}
		}
	}
	$content = str_replace(']]>',']]>',$content);
	return $content;
}
add_filter( 'the_content','ini_nofollow');

// 对图片链接添加fancybox属性
function ini_fancybox($content){
	global $post;
	$pattern = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>(.*?)<\/a>/i";
	$replacement = '<a$1href=$2$3.$4$5 rel="section" class="fbox-img"$6>$7</a>';
	$content = preg_replace($pattern,$replacement,$content);
	return $content;
}

// 索引目录
function ini_index($content){
	$arr = array();
	$makeLi = '';
	$replace = "/<h3>(.*?)<\/h3>/im";
	if( preg_match_all($replace, $content, $arr) ){
		foreach($arr[1] as $num => $title){
			$content = str_replace($arr[0][$num], '<h3 id="title-'.$num.'">'.$title.'</h3>', $content);
			$makeLi .= '<li><a href="#title-'.$num.'">'.$title."</a></li>\n";
		}
		$content = "\n<div id=\"ini-index\">
		<ul>\n".$makeLi."</ul>
		</div>\n".$content;
	}
	return $content;
}

?>